<template>
    <el-card>
      <template #header>
        <div class="card-header">
          <span>房源列表</span>
        </div>
      </template>
  
      <!-- 搜索 -->
      <div>
        <el-form inline>
          <el-form-item label="房主">
            <el-input v-model="searchForm.hostName" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="出租类型">
            <el-select v-model="searchForm.rentType">
              <el-option label="整套出租" value="1"></el-option>
              <el-option label="单间出租" value="2"></el-option>
              <el-option label="合住房间" value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="房源类型">
            <el-select v-model="searchForm.homeType">
              <el-option label="别墅" value="1"></el-option>
              <el-option label="公寓" value="2"></el-option>
              <el-option label="住宿加早餐" value="3"></el-option>
              <el-option label="Loft" value="4"></el-option>
              <el-option label="小木屋" value="5"></el-option>
              <el-option label="城堡" value="6"></el-option>
              <el-option label="宿舍" value="7"></el-option>
              <el-option label="蒙古包" value="8"></el-option>
              <el-option label="帐篷" value="9"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="面积">
            <el-input
              v-model="searchForm.minSpace"
              size="small"
              style="width: 60px"
            />
            &nbsp;-&nbsp;
            <el-input
              v-model="searchForm.maxSpace"
              size="small"
              style="width: 60px"
            />
          </el-form-item>
          <el-form-item label="价格">
            <el-input
              v-model="searchForm.minPrice"
              size="small"
              style="width: 60px"
            />
            &nbsp;-&nbsp;
            <el-input
              v-model="searchForm.maxPrice"
              size="small"
              style="width: 60px"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status">
              <el-option label="未发布" value="1"></el-option>
              <el-option label="待审核" value="2"></el-option>
              <el-option label="已上线" value="3"></el-option>
              <el-option label="已下线" value="4"></el-option>
              <el-option label="审核失败" value="5"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div
          style="
            width: 100%;
            padding-bottom: 20px;
            display: flex;
            justify-content: flex-end;
          "
        >
          <el-button type="primary" @click="searchSubmit">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </div>
      </div>
  
      <!-- 列表 -->
      <VTable
        :tableData="tableData"
        :options="options"
        @getSelection="handleSelection"
      >
        <template #menubtn>
          <el-button type="primary" @click="handleAdd">新增</el-button>
          <el-button type="warning" @click="handleBatchDelete"
            >批量删除</el-button
          >
        </template>
  
        <template #operate="scope">
          <el-button
            size="small"
            link
            type="primary"
            :icon="View"
            @click="handleDetail(scope.row)"
            >查看</el-button
          >
          <el-button
            size="small"
            link
            type="primary"
            :icon="Edit"
            @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button
            size="small"
            link
            type="danger"
            :icon="Delete"
            @click="handleDelete(scope.row.id)"
            >删除</el-button
          >
        </template>
      </VTable>
  
      <!-- 弹窗 -->
      <el-dialog v-model="dialogVisible" :title="dialogTitle">
        <!-- 编辑/新增 -->
        <el-form
          v-if="actionType === '新增' || actionType === '编辑'"
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="auto"
        >
          <el-form-item
            v-for="item in filterOptions"
            :key="item"
            :label="item.label"
            :prop="item.prop"
          >
            <el-autocomplete
              v-if="item.prop === 'hostName'"
              v-model="ruleForm.hostName"
              :fetch-suggestions="querySearchUsername"
              clearable
              class="inline-input w-50"
              @select="handleSelectUsername"
            />
            <el-upload
              v-else-if="item.prop === 'photos'"
              v-model:file-list="fileList"
              action="#"
              auto-upload="false"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :http-request="modeUpload"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
            <el-select
              v-model="ruleForm.rentType"
              v-else-if="item.prop === 'rentType'"
            >
              <el-option :value="1" label="整套出租" />
              <el-option :value="2" label="单间出租" />
              <el-option :value="3" label="合住房间" />
            </el-select>
  
            <el-select
              v-model="ruleForm.homeType"
              v-else-if="item.prop === 'homeType'"
            >
              <el-option
                v-for="item in homeOptions"
                :key="item"
                :value="item.value"
                :label="item.label"
              ></el-option>
            </el-select>
            <el-input-number
              v-else-if="item.type == 'number'"
              v-model="ruleForm[item.prop]"
            ></el-input-number>
            <el-checkbox-group
              v-else-if="item.prop == 'facility'"
              v-model="ruleForm.facility"
              @change="handleCheckedFacilityChange"
            >
              <el-checkbox v-for="f in facility" :key="f.label" :label="f.key">
                <SvgIcon :icon-class="f.icon" size="20px"></SvgIcon
                >{{ f.label }}</el-checkbox
              >
            </el-checkbox-group>
            <el-time-picker
              v-else-if="item.type === 'timePic'"
              v-model="ruleForm[item.prop]"
              placeholder="请选择时间"
            >
            </el-time-picker>
            <el-input
              v-else-if="item.prop === 'features'"
              type="textarea"
              v-model="ruleForm[item.prop]"
              :rows="4"
            ></el-input>
            <el-select
              v-else-if="item.prop === 'status'"
              v-model="ruleForm.status"
            >
              <el-option :value="2" label="待审核"></el-option>
              <el-option :value="3" label="已上线"></el-option>
              <el-option :value="4" label="已下线"></el-option>
              <el-option :value="5" label="审核失败"></el-option>
            </el-select>
            <el-cascader
              v-else-if="item.prop == 'mapAddress'"
              placeholder="请选择地区"
              size="default"
              :options="regionData"
              v-model="ruleForm.mapAddress"
              @change="handleChange"
            >
            </el-cascader>
            <div v-else-if="item.prop == 'map'" id="allmap"></div>
  
            <el-input
              v-else-if="item.prop == 'country'"
              v-model="ruleForm.country"
              @click="handleBlur"
            ></el-input>
  
            <el-input
              v-else-if="item.isForm == true"
              v-model="ruleForm[item.prop]"
            ></el-input>
          </el-form-item>
        </el-form>
  
        <!-- 详情 -->
        <!-- 详情 -->
        <Description
          v-if="actionType === '查看'"
          :options="fOptions"
          :dataItem="dataItem"
        >
        </Description>
  
        <!-- 按钮 -->
        <template #footer>
          <el-button
            v-if="actionType === '新增' || actionType === '编辑'"
            @click="resetForm(ruleFormRef)"
            >关闭</el-button
          >
          <el-button v-if="actionType === '查看'" @click="dialogVisible = false"
            >关闭</el-button
          >
          <el-button
            v-if="actionType === '新增' || actionType === '编辑'"
            type="primary"
            @click="submitForm(ruleForm)"
          >
            确定
          </el-button>
        </template>
      </el-dialog>
    </el-card>
  </template>
  
  <script setup lang="ts">
  import { ref, onMounted, reactive } from "vue";
  import {
    getAllHomestay,
    deleteHomestay,
    batchHomestay,
    searchHomestay,
  } from "../../api/homestayManage/index";
  import VTable from "../../components/VTable/index.vue";
  import Description from "../../components/Description/index.vue";
  import { Delete, Edit, View, Plus } from "@element-plus/icons-vue";
  import { ElMessage, ElMessageBox } from "element-plus";
  import SvgIcon from "../../components/SvgIcon/index.vue";
  import { getHostList, searchHost } from "../../api/userManage/index";
  import { regionData, CodeToText, TextToCode } from "element-china-area-data";
  
  import type {
    FormInstance,
    FormRules,
    UploadProps,
    UploadUserFile,
    UploadFile,
  } from "element-plus";
  
  const tableData = ref<any>([]);
  const options = [
    {
      prop: "hostName",
      label: "房主",
      isTable: true,
      isForm: true,
      isSearch: true,
      width: 150,
    },
    {
      prop: "title",
      label: "标题",
      isTable: true,
      isForm: true,
      width: 240,
    },
    {
      prop: "photos",
      label: "图片",
      isForm: true,
    },
    {
      prop: "address",
      label: "地址",
      isTable: true,
      isForm: false,
      isSearch: true,
      width: 240,
    },
    {
      prop: "features",
      label: "房屋特色",
      // isTable: true,
      isForm: true,
    },
    {
      prop: "rentType",
      label: "出租类型",
      isTable: true,
      isForm: true,
      isSearch: true,
      width: 120,
    },
    {
      prop: "homeType",
      label: "房源类型",
      isTable: true,
      isForm: true,
      isSearch: true,
      width: 120,
    },
    {
      prop: "space",
      label: "面积（平方米）",
      isTable: true,
      isForm: true,
      isSearch: true,
      width: 150,
      type: "number",
    },
    {
      prop: "mostPeople",
      label: "最多可住人数",
      isForm: true,
      isSearch: true,
      type: "number",
    },
    {
      prop: "minDay",
      label: "最短入住天数",
      isForm: true,
      isSearch: true,
      type: "number",
    },
    {
      prop: "price",
      label: "价格（元/晚）",
      isTable: true,
      isForm: true,
      isSearch: true,
      width: 120,
      type: "number",
    },
    {
      prop: "facility",
      label: "配套设施",
      isForm: true,
    },
    {
      prop: "earlyTime",
      label: "最早入住时间",
      isForm: true,
      type: "timePic",
    },
    {
      prop: "lastTime",
      label: "最晚退房时间",
      isForm: true,
      type: "timePic",
    },
    {
      prop: "status",
      type: "more",
      label: "状态",
      isTable: true,
      isForm: true,
      isSearch: true,
      width: 120,
    },
    {
      prop: "hot",
      label: "热度",
      isTable: true,
      isForm: true,
      width: 120,
      type: "number",
    },
    {
      prop: "mapAddress",
      label: "地址",
      isForm: true,
      isDetail: false,
    },
    {
      prop: "country",
      label: "详细地址",
      isForm: true,
    },
    {
      prop: "map",
      label: "位置",
      isForm: true,
    },
  ];
  
  const homeOptions = [
    {
      value: 1,
      label: "别墅",
    },
    {
      value: 2,
      label: "公寓",
    },
    {
      value: 3,
      label: "住宿加早餐",
    },
    {
      value: 4,
      label: "Loft",
    },
    {
      value: 5,
      label: "小木屋",
    },
    {
      value: 6,
      label: "城堡",
    },
    {
      value: 7,
      label: "宿舍",
    },
    {
      value: 8,
      label: "蒙古包",
    },
    {
      value: 9,
      label: "帐篷",
    },
    {
      value: 10,
      label: "其他",
    },
  ];
  const checkedFacility = ref([]);
  const facility = [
    { key: 1, label: "毛巾", icon: "icon-maojin" },
    { key: 2, label: "牙具", icon: "icon-yaju" },
    { key: 3, label: "沐浴露", icon: "icon-muyulou" },
    { key: 4, label: "洗发水", icon: "icon-tubiaoCSban-" },
    { key: 5, label: "拖鞋", icon: "icon-tuoxie" },
    { key: 6, label: "吹风机", icon: "icon-chuifengji" },
    { key: 7, label: "淋浴", icon: "icon-linyu" },
    { key: 8, label: "电视", icon: "icon-dianshiji" },
    { key: 9, label: "空调", icon: "icon-kongtiao" },
    { key: 10, label: "冰箱", icon: "icon-bingxiang" },
    { key: 11, label: "洗衣机", icon: "icon-xiyiji" },
    { key: 12, label: "WIFI", icon: "icon-wifi" },
    { key: 13, label: "厨具", icon: "icon-chuju" },
    { key: 14, label: "免费早餐", icon: "icon-zaocan" },
    { key: 15, label: "暖气", icon: "icon-nuanqi" },
    { key: 16, label: "烘干机", icon: "icon-hongganji" },
    { key: 17, label: "游泳池", icon: "icon-youyongchi" },
    { key: 18, label: "健身房", icon: "icon-jianshenfang" },
    { key: 19, label: "停车场", icon: "icon-tingchechang" },
    { key: 20, label: "电梯", icon: "icon-elevator" },
    { key: 21, label: "卫生纸", icon: "icon-weishengzhi" },
    { key: 22, label: "灭火器", icon: "icon-miehuoqi" },
    { key: 23, label: "浴缸", icon: "icon-yugang" },
    { key: 24, label: "无障碍设施", icon: "icon-wuzhangaisheshi" },
  ];
  const handleCheckedFacilityChange = (value: string[]) => {
    console.log(ruleForm.facility);
  };
  
  //自动补全
  const querySearchUsername = async (name, callback) => {
    const list = [];
    if (name) {
      const res = await searchHost({ username: name });
      res.data.data.forEach((item: any) => {
        list.push({ value: item.username, id: item.id });
      });
    } else {
      const res = await getHostList();
      res.data.data.forEach((item: any) => {
        list.push({ value: item.username, id: item.id });
      });
    }
    callback(list);
  };
  //选中
  const handleSelectUsername = (item, $event) => {
    console.log(item);
    ruleForm.userId = item.id;
  };
  
  const dialogTitle = ref("查看"); // 弹出层标题
  const actionType = ref(""); // 操作按钮的类型
  const setDialogTile = (type: string) => {
    dialogTitle.value = type;
    actionType.value = type;
    dialogVisible.value = true;
  };
  
  const dialogVisible = ref<boolean>(false);
  const dataItem = ref<object>({});
  
  const ruleFormRef = ref<FormInstance>();
  let ruleForm = reactive({
    userId: "",
    hostName: "",
    title: "",
    photos: ref<UploadUserFile[]>([]),
    address: "",
    features: "",
    rentType: "",
    homeType: "",
    space: "",
    mostPeople: "",
    minDay: "",
    price: "",
    facility: "",
    status: "",
    hot: "",
    province: "",
    city: "",
    area: "",
    country: "",
  });
  const rules = reactive<FormRules>({});
  //新增
  const handleAdd = () => {
    ruleForm = reactive({
      hostName: "",
      title: "",
      photos: ref<UploadUserFile[]>([]),
      address: "",
      features: "",
      rentType: "",
      homeType: "",
      space: "",
      mostPeople: "",
      minDay: "",
      price: "",
      facility: "",
      status: "",
      hot: "",
      province: "",
      city: "",
      area: "",
      country: "",
    });
    loadMapScript(); // 加载百度地图资源
    setDialogTile("新增");
  };
  //详情
  const handleDetail = (scope: any) => {
    dataItem.value = scope;
    setDialogTile("查看");
  };
  //删除
  const handleDelete = async (id: number) => {
    ElMessageBox.confirm("确认删除此项数据?", "系统提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(async () => {
        console.log(id);
        const res = await deleteHomestay(id);
        if (res.data.success == true) {
          ElMessage({
            message: res.data.msg,
            type: "success",
          });
        } else {
          ElMessage.error(res.data.msg);
        }
        onLoad();
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "取消删除",
        });
      });
  };
  //子组件传值--多选
  const ids = ref<any>([]);
  const handleSelection = (val: any) => {
    // console.log("子组件传值：", val);
    const selecction: any = [];
    val.forEach((item: any) => {
      selecction.push(item.id);
    });
    ids.value = selecction;
    console.log("ids.value:", ids.value);
  };
  // 批量删除
  const handleBatchDelete = async () => {
    if (ids.value.length == 0) {
      ElMessage({
        type: "info",
        message: "请选择数据",
      });
      return;
    }
    ElMessageBox.confirm("确认删除这些数据?", "系统提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(async () => {
        const res = await batchHomestay(ids.value);
        if (res.data.success) {
          ElMessage({
            message: res.data.msg,
            type: "success",
          });
        } else {
          ElMessage.error(res.data.msg);
        }
        onLoad();
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "取消删除",
        });
      });
  };
  //编辑
  const handleEdit = async (scope: any) => {
    ruleForm = scope;
    console.log(ruleForm);
    setDialogTile("编辑");
  };
  //搜索
  const searchForm = ref<any>({
    hostName: "",
    rentType: "",
    homeType: "",
    minSpace: "",
    maxSpace: "",
    minPrice: "",
    maxPrice: "",
    status: "",
  });
  const searchSubmit = async () => {
    const res = await searchHomestay(searchForm.value);
    tableData.value = res.data.data;
  };
  //重置搜索
  const resetSearch = async () => {
    searchForm.value = {
      hostName: "",
      rentType: "",
      homeType: "",
      minSpace: "",
      maxSpace: "",
      minPrice: "",
      maxPrice: "",
      status: "",
    };
    await onLoad();
  };
  //关闭弹窗
  const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.resetFields();
    dialogVisible.value = false;
  };
  
  const onLoad = async () => {
    const res = await getAllHomestay();
    tableData.value = res.data.data;
    console.log("table", tableData.value);
  };
  
  const filterOptions = ref<any>([]);
  const fOptions = ref<any>([]);
  onMounted(async () => {
    await onLoad();
    options.map((item: any) => {
      if (item.isForm == true) {
        filterOptions.value.push(item);
      }
      if (item.isDetail !== false) {
        fOptions.value.push(item);
      }
    });
  });
  
  const contentAddress = ref();
  const city = ref();
  const handleChange = (value) => {
    ruleForm.province = value[0];
    ruleForm.city = value[1];
    ruleForm.area = value[2];
    console.log(value);
  
    contentAddress.value =
      CodeToText[value[0]] +
      CodeToText[value[1]] +
      CodeToText[value[2]] +
      ruleForm.country;
    city.value = CodeToText[value[1]];
    ruleForm.address = contentAddress.value;
    init(contentAddress.value, city.value);
  };
  const handleBlur = () => {
    init(contentAddress.value, ruleForm.country);
  };
  
  // 初始化地图
  let map: any = null;
  const init = (address = "北京市海淀区上地10街10号", city = "北京市") => {
    const { BMap } = window as any; // 注意要带window，不然会报错（注意官方api,会有改动，之前是Bmap,后面3.0版本改为了BMap,最好查文档或者打印一下window）
    map = new BMap.Map("allmap"); // allmap必须和dom上的id一直
    map.centerAndZoom(new BMap.Point(116.404, 39.915), 20); // 初始化地图,设置中心点坐标和地图级别
    map.setCurrentCity("长沙");
    map.enableScrollWheelZoom(true);
  
    var myGeo = new BMap.Geocoder();
    myGeo.getPoint(
      address,
      function (point: any) {
        if (point) {
          ruleForm.lng = point.lng;
          ruleForm.lat = point.lat;
          console.log(point.lng, point.lat);
          map.centerAndZoom(point, 16);
          map.addOverlay(new BMap.Marker(point));
        }
      },
      city
    );
    map.addEventListener("click", function (e: any) {
      // prompt("鼠标单击地方的经纬度为：", e.point.lng + "," + e.point.lat);
      map.centerAndZoom(new BMap.Point(e.point.lng, e.point.lat), 20);
      myGeo.getLocation(e.point, function (res: any) {
        const addrComponent = res.addressComponents;
        console.log(addrComponent);
  
        const surroundingPois = res.surroundingPois;
        const province = addrComponent.province;
        const city = addrComponent.city;
        const district = addrComponent.district;
        ruleForm.province = TextToCode[province].code;
        ruleForm.city = TextToCode[province][city].code;
        ruleForm.area = TextToCode[province][city][district].code;
        ruleForm.mapAddress = [ruleForm.province, ruleForm.city, ruleForm.area];
        let addr = addrComponent.street;
        if (surroundingPois.length > 0 && surroundingPois[0].title) {
          if (addr) {
            addr += `-${surroundingPois[0].title}`;
          } else {
            addr += `${surroundingPois[0].title}`;
          }
        } else {
          addr += addrComponent.streetNumber;
        }
        ruleForm.country = addr;
      });
    });
  };
  
  const loadMapScript = () => {
    // 此处在所需页面引入资源就是，不用再public/index.html中引入
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.className = "loadmap"; // 给script一个类名
    script.src =
      "https://api.map.baidu.com/getscript?v=3.0&ak=iVUHbZKxuGPpDsbnsgfRcfQUgfb55a18";
    // 此处需要注意：申请ak时，一定要应用类别一定要选浏览器端，不能选服务端，不然地图会报ak无效
    script.onload = () => {
      // 使用script.onload，待资源加载完成，再初始化地图
      init();
    };
    let loadmap = document.getElementsByClassName("loadmap");
    if (loadmap) {
      // 每次append script之前判断一下，避免重复添加script资源标签
      for (var i = 0; i < loadmap.length; i++) {
        document.body.removeChild(loadmap[i]);
      }
    }
  
    document.body.appendChild(script);
  };
  </script>
  
  <style lang="scss" scoped>
  #allmap {
    // 注意给dom宽高，不然地图不出来
    width: 500px;
    height: 300px;
  }
  </style>
  